package edu.usmp.p2.util;

import java.io.IOException;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.logging.AbstractSessionLog;
import org.eclipse.persistence.logging.SessionLog;
import org.eclipse.persistence.logging.SessionLogEntry;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.sessions.Session;

public class JPAEclipseLinkSessionCustomizer implements SessionCustomizer{


	public void customize(Session session) throws Exception {
		// TODO Auto-generated method stub
		JNDIConnector connector = null;
	    Context context = null;
	    try {
	      context = new InitialContext();
	      if(context != null) {
	        connector = (JNDIConnector)session.getLogin().getConnector();
	        connector.setLookupType(JNDIConnector.STRING_LOOKUP);
	        System.err.println("******************** JPAEclipseLinkSessionCustomizer: configured " + connector.getName());
	      }
	    }catch(Exception e) {
	      e.printStackTrace();
	    }
		SessionLog log =new CustomAbstractSessionLog();
		log.setLevel(SessionLog.FINEST);
		session.setSessionLog(log);
	}

	public class CustomAbstractSessionLog extends AbstractSessionLog
	implements SessionLog {
		private Log log = LogFactory.getLog(getClass());

		public CustomAbstractSessionLog(){
			Properties logConfig = new Properties();
			try {
				logConfig.load(this.getClass().getResourceAsStream("/META-INF/log4j.config"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			PropertyConfigurator.configure(logConfig);
		}

		@Override
		public void log(SessionLogEntry sessionlogentry) {
			// TODO Auto-generated method stub
			if(log.isDebugEnabled())log.debug(sessionlogentry.getMessage());
		}
	}
}